package com.example.controller;

import com.example.entity.MicroResponse;
import com.example.entity.info.UtiPubRecord;
import com.example.entity.info.UtiPubUser;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.example.entity.transAirspaceUtilization;
import com.example.service.AirspaceUtilizationService;
import com.example.util.MicroResponseUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class AirspaceUtilizationController {

    @Autowired
    private AirspaceUtilizationService airspaceUtilizationService;

    private final Logger logger = LoggerFactory.getLogger(AirspaceUtilizationController.class);

    //关键字搜索和排序
    @PostMapping("module2/utisearch")
    @ResponseBody
    public ResponseEntity searchuti(
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) String sort,
            @RequestParam(required = false) boolean order) {

        logger.info("Received search request - keyword: {}, sort: {}, order: {}", keyword, sort, order);
        List<transAirspaceUtilization> result = airspaceUtilizationService.keywordSearch(keyword, sort, order);
        return ResponseEntity.ok(MicroResponseUtils.success(result));
    }

    //获取发布用户信息表
    @GetMapping("module2/GetPubUser")
    @ResponseBody
    public ResponseEntity GetPubUser() {
        List<UtiPubUser> users = airspaceUtilizationService.getUtiPubUser();
        return ResponseEntity.ok(MicroResponseUtils.success(users));
    }

    //添加发布用户
    @PostMapping("module2/addUser")
    public ResponseEntity saveName(@RequestParam String name) {
        try {
            // 保存名字并返回所有记录
            List<UtiPubUser> allUsers = airspaceUtilizationService.saveNameAndReturnAll(name);
            // 返回数据使用 MicroResponseUtils.success
            return ResponseEntity.ok(MicroResponseUtils.success(allUsers));
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(MicroResponseUtils.error("Error saving name"));
        }
    }

    //发布记录更新
    @PostMapping("module2/PubRecord")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> publishUser(
            @RequestParam int instructionId,
            @RequestParam String userName) {

        logger.info("Received publish request - instructionId: {}, userName: {}", instructionId, userName);
        // 调用 service 保存或更新发布记录
        Map<Integer, List<UtiPubRecord>> records = airspaceUtilizationService.saveOrUpdateUserPublishRecord(instructionId, userName);
        // 对结果进行 internal_id 排序
        records.forEach((key, list) -> list.sort(Comparator.comparingInt(UtiPubRecord::getInternalId)));
        // 使用 MicroResponseUtils 返回数据
        MicroResponse<Map<Integer, List<UtiPubRecord>>> microResponse = MicroResponseUtils.success(records);
        // 构建新的返回数据
        Map<String, Object> responseData = new HashMap<>();
        responseData.put("code", microResponse.getCode()); // 提取代码
        responseData.put("message", microResponse.getMessage()); // 提取消息
        responseData.put("data", microResponse.getData()); // 提取数据
        // 返回 ResponseEntity
        return ResponseEntity.ok(responseData);
    }

    //根据需求说明id返回历史记录
    @GetMapping("module2/GetRecord")
    public ResponseEntity<?> getRecords(@RequestParam Integer instructionId, @RequestParam(defaultValue = "true") boolean order) {
        List<UtiPubRecord> records = airspaceUtilizationService.getRecordsByInstructionIdWithSorting(instructionId, order);
        return ResponseEntity.ok(MicroResponseUtils.success(records));
    }

}
